package com.example.shardingjdbcdemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.shardingjdbcdemo.entity.User;
import com.example.shardingjdbcdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 新增用户 - 写操作，应该走主库
     */
    @PostMapping
    public String addUser(@RequestBody User user) {
        //新增，设置下ID的值
        user.setId(System.currentTimeMillis());
        userService.save(user);
        return "新增成功，用户ID：" + user.getId();
    }

    /**
     * 查询用户 - 读操作，应该走从库
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getById(id);
    }

    /**
     * 查询所有用户 - 读操作，应该走从库
     */
    @GetMapping
    public List<User> getAllUsers() {
        return userService.list(new QueryWrapper<>());
    }

    /**
     * 更新用户 - 写操作，应该走主库
     */
    @PutMapping
    public String updateUser(@RequestBody User user) {
        userService.updateById(user);
        return "更新成功";
    }

    /**
     * 删除用户 - 写操作，应该走主库
     */
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        userService.removeById(id);
        return "删除成功";
    }
}
